package com.lixiaoyao.reggie.exhandler;

import com.lixiaoyao.reggie.common.CustomException;
import com.lixiaoyao.reggie.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler{

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exHandler(SQLIntegrityConstraintViolationException ex){

        String message = ex.getMessage();
        if(message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String str = split[2]+"用户已存在";
            return R.error(str);
        }
        log.info("异常信息 {}",ex.getMessage() );

        return R.error("出错了");
    }
    @ExceptionHandler(CustomException.class)
    public R<String> customExHandler(CustomException ex){

        String message = ex.getMessage();

        log.info("异常信息 {}",ex.getMessage() );

        return R.error(message);
    }
    @ExceptionHandler(Exception.class)
    public R<String> finalHandler(Exception exception){
        log.info(exception.getMessage());
        return R.error("未知错误,请联系管理员");
    }

}
